package com.teemor.im.remoting.window;

import com.teemor.im.common.command.EventType;
import com.teemor.im.common.command.RequestType;
import com.teemor.im.common.command.RemoteCommand;
import com.teemor.im.common.model.ImMessage;
import com.teemor.im.common.util.JsonUtil;
import com.teemor.im.executor.CommandDispatcher;
import com.teemor.im.executor.CommandTask;
import com.teemor.im.remoting.session.ServerSession;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @ename zhoulk
 * @cname 周李科
 * @date 2020/6/15 11:12
 */
public class WindowManager {

    /**
     * 所有会话窗口
     */
    private Map<Long, SessionWindow> windowMap = new ConcurrentHashMap<>();

    private static final WindowManager windowManager = new WindowManager();

    public SessionWindow getWindow(Long windowId) {
       return windowMap.get(windowId);
    }

    public static WindowManager getInstance() {
        return windowManager;
    }

    public static void addToWindow(Long windowId, ServerSession session) {
        SessionWindow sessionWindow = windowManager.getWindow(windowId);
        if (sessionWindow == null) {
            sessionWindow = createWindow(windowId,1);
        }
        sessionWindow.subscribe(session);
    }

    public static void pushMessage(ServerSession session, ImMessage message) {
        windowManager.getWindow(message.getTargetId()).pushMessage(session, message);
    }

    public static void forwardMessage(ImMessage message) {
        windowManager.getWindow(message.getTargetId()).forwardMessage(message);
    }

    public static List<ImMessage> pullMessage(Long windowId, ServerSession session) {
        return windowManager.getWindow(windowId).pullMessage(session);
    }

    /**
     * 创建一个新窗口
     * @param model 窗口模式
     * @return
     */
    public static SessionWindow createWindow(Long windowId, Integer model) {
        SessionWindow sessionWindow = new SessionWindow(windowId,model);
        windowManager.windowMap.put(sessionWindow.getId(), sessionWindow);
        
        RemoteCommand command = new RemoteCommand();
        command.setRequestType(RequestType.SINGE);
        command.setEventType(EventType.NEW_WINDOW);
        command.setSendTime(System.currentTimeMillis());
        command.setContent(JsonUtil.pojoToJson(sessionWindow));
        CommandTask commandTask = new CommandTask(command, EventType.NOTIFY, null);
        CommandDispatcher.doDispatcher(commandTask);
        return sessionWindow;
    }

    public static void addWindow(SessionWindow window) {
        windowManager.windowMap.put(window.getId(), window);
    }

    public static List<Long> getWindowIds() {
        return windowManager.windowMap.values().stream().map(SessionWindow::getId).collect(Collectors.toList());
    }
}
